<template>
  <div>
    <el-card class="box-card" shadow="always" style="margin:1px;" :body-style="bodyStyle">
      <div slot="header">
        <span>角色设置</span>
        <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
      </div>
      <div class="headerOperation">
        <div style="float:left;margin-left:10px;">
          <el-input v-model="searchKey" placeholder="请输入你要查找的内容" style="width:200px;margin-right:10px;" />
          <el-button type="primary" @click="handleFilter" @keyup.enter.native="handleFilter">筛选</el-button>
        </div>
        <div style="float:right;margin-right:10px;">
          <el-button type="primary" @click="handleAdd">添加</el-button>
          <el-button type="primary" @click="handleRefresh">刷新</el-button>
        </div>
      </div>
    </el-card>
    <div>
      <el-table :data="rolesList">
        <el-table-column label="Id" prop="id" />
        <el-table-column label="角色名称" prop="roleName" />
        <el-table-column label="介绍" prop="descripiton" />
        <el-table-column align="center" label="操作" width="300px">
          <template slot-scope="{row,$index}">
            <el-button type="primary" @click="handleEdit(row,$index)">编辑</el-button>
            <el-button type="primary" @click="handlepower(row,$index)">权限</el-button>
            <el-button type="danger" @click="handleDel(row.id,$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="收货地址" :visible.sync="dialogFormVisible" @close="handleDialogClose">
        <el-form ref="formDialog" :model="formData">
          <el-form-item label="角色名称" prop="roleName" :label-width="lableWidth">
            <el-input v-model="formData.roleName" class="inputWidth" />
          </el-form-item>
          <el-form-item label="介绍" prop="descripiton" :label-width="lableWidth">
            <el-input v-model="formData.descripiton" class="inputWidth" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleFormCancel">取 消</el-button>
          <el-button type="primary" @click="handleFormConfirm">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="权限" :visible.sync="dialogFormPower" @close="handleDialogClose">
        <el-tree
          ref="permissionTree"
          :props="permissionProp"
          :data="permissionList"
          node-key="name"
          :default-checked-keys="permissionarr"
          show-checkbox
        />
        <div slot="footer" class="dialog-footer">
          <el-button @click="handlePermissionFormCancel">取 消</el-button>
          <el-button type="primary" @click="handlePermissionFormConfirm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getroles, postroles, putroles, deleteroles, saveRolepermission } from '@/api/role'
import routes from '@/router/routes'
export default {
  data() {
    return {
      rolesList: [],
      searchKey: '',
      rolespermissionId: 0,
      permissionarr: [],
      dialogFormVisible: false,
      dialogFormPower: false,
      isAddBtnClick: true,
      lableWidth: '20%',
      currentIndex: -1,
      formData: {
        id: 0,
        roleName: '',
        descripiton: ''
      },
      permissionProp: {
        label: 'title'
      },
      bodyStyle: {
        padding: '0px'
      }
    }
  },
  computed: {
    // 获取用户权限列表
    permissionList: function() {
      var getAccessList = function(arrs) {
        var arr = []
        arrs.forEach(item => {
          var tempItem = {}
          if (item.meta && item.meta.access) {
            tempItem.title = item.meta.title ? item.meta.title : item.name
            tempItem.name = item.name
            tempItem.access = item.meta.access

            arr.push(tempItem)
          }
          if (item.children && item.children.length > 0) {
            tempItem.children = getAccessList(item.children)
          }
        })
        return arr
      }
      // 调用函数传回路由参数
      return getAccessList(routes)
    }
  },
  created: function() {
    // this.fetchList()
    // 将数据赋值初始框
    this.rolesList = this.fetchList()
  },
  methods: {
    fetchList: function() {
      getroles().then(res => {
        this.rolesList = res.data
      })
    },
    // 筛选角色信息
    handleFilter: function() {
      // console.log(this.searchKey)
      var originList = this.rolesList
      var list = originList.filter(item => item.roleName.indexOf(this.searchKey) >= 0)
      this.rolesList = list
    },
    // 打开添加弹框
    handleAdd: function() {
      // this.resetFormFields()
      this.dialogFormVisible = true
      this.isAddBtnClick = true
    },
    // 角色刷新
    handleRefresh: function() {
      this.fetchList()
      this.$message.success('刷新成功！')
    },
    // 打开编辑弹框
    handleEdit: function(item, index) {
      // 获取下标
      this.currentIndex = index
      this.dialogFormVisible = true
      // 编辑的时候，给form赋值需要延后执行，否则重置表单将不生效
      this.$nextTick(() => {
        this.formData = Object.assign({}, item)
      })
      this.isAddBtnClick = false
    },
    // 打开权限弹框
    handlepower(item, index) {
      this.dialogFormPower = true
      this.permissionarr = []
      this.$nextTick(() => {
        this.formData = Object.assign({}, item)
      })
      var data = {
        roleId: item.id,
        access: null
      }
      console.log(this.permissionarr)
      saveRolepermission(data).then(res => {
        this.permissionarr = res.data
        console.log(this.permissionarr)
      })
    },
    // 角色删除
    handleDel: function(id, index) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteroles(id).then(res => {
          console.log(res)
          this.rolesList.splice(index, 1)
          this.$message.success('删除成功!')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    handleFormCancel: function() {
      this.dialogFormVisible = false
      // this.$refs[formName].resetFields()
    },
    // 角色增加与修改
    handleFormConfirm: function() {
      this.dialogFormVisible = false
      // 获取用户输入信息
      var temp = Object.assign({}, this.formData)
      // this.$refs[formName].resetFields()
      if (this.isAddBtnClick) {
        postroles(temp).then(res => {
          console.log(res)
          this.rolesList.push(res.data)
          this.$message.success('增加成功！')
        })
      } else {
        putroles(this.formData.id, temp).then(res => {
          console.log(res)
          this.rolesList.splice(this.currentIndex, 1, res.data)
          this.$message.success('修改成功！')
        })
      }
    },
    // 权限弹窗关闭
    handlePermissionFormCancel() {
      this.dialogFormPower = false
    },
    // 角色权限增加
    handlePermissionFormConfirm() {
      this.dialogFormPower = false
      // 获取角色Id
      this.rolespermissionId = this.formData.id
      // 获取目前被选中的节点所组成的数组
      var accessList = this.$refs.permissionTree.getCheckedNodes()
      var arr = []
      accessList.forEach(item => {
        var row = {
          title: item.title,
          name: item.name
        }
        arr.push(row)
      })

      var data = {
        roleId: this.rolespermissionId,
        access: arr
      }
      console.log(data)
      saveRolepermission(data).then(res => {
        console.log(res)
      })
    },
    // 对话窗口关闭时 重置表单项
    handleDialogClose: function() {
      this.resetFormFields()
    },
    resetFormFields() {
      var formDialog = this.$refs.formDialog
      var permissionTree = this.$refs.permissionTree
      if (formDialog) {
        formDialog.resetFields()
      } else if (permissionTree) {
        permissionTree.setCheckedKeys([])
      }
    }
  }
}
</script>

